<?php


class phpinchains_util_generator_DBGenerator {

    protected static $bundlecode      = '';
    protected static $bundleerrorcode = '';

    public static function formListingJavascript () {
/*<link rel="stylesheet" type="text/css" href="'.$GLOBALS['generatorCnf']['options']['js-cal-path'].'css/jscal2.css" />
<link rel="stylesheet" type="text/css" href="'.$GLOBALS['generatorCnf']['options']['js-cal-path'].'css/border-radius.css" />
<script type="text/javascript" src="'.$GLOBALS['generatorCnf']['options']['js-cal-path'].'js/jscal2.js"></script>
<script type="text/javascript" src="'.$GLOBALS['generatorCnf']['options']['js-cal-path'].'js/lang/de.js"></script>*/
        return '
<script type="text/javascript">
    function openChooser(url, windowname) {
        var mein_fenster = window.open(url, windowname, \'width=800, height=620, scrollbars\');
        return false;
    }
    function removeChoise(textid, fieldid) {
        document.getElementById(textid ).innerHTML=\'\';
        document.getElementById(fieldid).value=\'\';
        return;
    }
</script>';
    }

    public static function getBundleCode () {
        return self::$bundlecode;
    }

    public static function getBundleErrorCode () {
        return self::$bundleerrorcode;
    }

    public static function resetState () {
        self::$bundleerrorcode = '';
        self::$bundlecode      = '';
    }

    public static function genBundleMessage($usebundles, $key, $altstr) {
        return ($usebundles ? '<fmt:message'.(isset($GLOBALS['generatorCnf']['options']['bundle-value-resource-path'])?' assetUrl="'.$GLOBALS['generatorCnf']['options']['bundle-value-resource-path'].'"':'').' key="'.$key.'"/>' : $altstr);
    }

    /**
     * Generates the code for the specified table information.
     *
     * @param string $table
     * @param array $rows
     */
    public static function generateCode ($table, $rows, $indexes = array()) {

    }

    /**
     * Saves the php to a php file.
     *
     * Adds code to a php block while saving.
     *
     * @param string $destfile File to save to. Is created, if not exists.
     * @param string $code     PHP code to save to the file.
     */
    public static function saveCode ($table, $destfile, $code, $force = false) {
        if ($force || !file_exists($destfile)) {
            print "create file '$destfile'\n";
            file_put_contents($destfile, '<?php'."\n\n".$code."\n\n".'?>');
        }
    }

    public static function genClassName ($name) {
        return self::upperFirstLetter($name);
    }

    public static function upperFirstLetter ($name) {
        $name[0] = strtoupper($name[0]);
        return $name;
    }

    public static function genActionMappingName ($name) {
        $name[0] = strtolower($name[0]);
        return $name;
    }

    public static function getSnippet ($part, $table) {
        if (!empty($GLOBALS['generatorCnf']['options']['psp-snippet-'.$part])) {
            if (is_array($GLOBALS['generatorCnf']['options']['psp-snippet-'.$part])) {
                if (!empty($GLOBALS['generatorCnf']['options']['psp-snippet-'.$part][$table])) {
                    return $GLOBALS['generatorCnf']['options']['psp-snippet-'.$part][$table]."\n";
                }
            } else
                return $GLOBALS['generatorCnf']['options']['psp-snippet-'.$part]."\n";
        }
    }

    public static function getSpecificSnippet ($psp, $part, $table) {
        if (!empty($GLOBALS['generatorCnf']['options']['psp-snippet-'.$psp])) {
            if (is_array($GLOBALS['generatorCnf']['options']['psp-snippet-'.$psp])) {
                if ($part == 'top') {
                    if (!empty($GLOBALS['generatorCnf']['options']['psp-snippet-'.$psp][$part])) {
                        $code .= $GLOBALS['generatorCnf']['options']['psp-snippet-'.$psp][$part]."\n";
                    }
                    if (!empty($GLOBALS['generatorCnf']['options']['psp-snippet-'.$psp][$table][$part])) {
                        $code .= $GLOBALS['generatorCnf']['options']['psp-snippet-'.$psp][$table][$part]."\n";
                    }
                } else {
                    if (!empty($GLOBALS['generatorCnf']['options']['psp-snippet-'.$psp][$part])) {
                        $code .= $GLOBALS['generatorCnf']['options']['psp-snippet-'.$psp][$part]."\n";
                    }
                    if (!empty($GLOBALS['generatorCnf']['options']['psp-snippet-'.$psp][$table][$part])) {
                        $code .= $GLOBALS['generatorCnf']['options']['psp-snippet-'.$psp][$table][$part]."\n";
                    }
                }
            }
        }
        return $code;
    }

    public static function getTagAttributes ($table, $rowname) {
        $code = '';
        if (!empty($GLOBALS['generatorCnf']['forms'][$table]['fields'][$rowname]['tag-attributes'])) {
            if (is_array($GLOBALS['generatorCnf']['forms'][$table]['fields'][$rowname]['tag-attributes'])) {
                foreach ($GLOBALS['generatorCnf']['forms'][$table]['fields'][$rowname]['tag-attributes'] as $n => $v) {
                    $code .= ' '.$n.'="'.$v.'"';
                }
            }
        }
        return $code;
    }

    // wg getTableName()
    /*
    // find first occurence of table to find true name of optiontext column
    public static function getOptiontextColumn ($table, $foreignkeyfield) {
        foreach ($GLOBALS['generatorCnf']['tables'][getTableName($table)] as $n => $v) {
            if ($v[0] == $GLOBALS['generatorCnf']['tables'][getTableName($table)][$foreignkeyfield][0]) {
                return $v[1];
            }
        }
        return '';
    }
*/


    // find first occurence of table to find true name of optiontext column
    public static function getOptiontextColumn ($table, $foreignkeyfield) {
        foreach ($GLOBALS['generatorCnf']['tables'][$table] as $n => $v) {
            if ($v[0] == $GLOBALS['generatorCnf']['tables'][$table][$foreignkeyfield][0]) {
                return isset($v[4])?$v[4]:$v[1];
            }
        }
        return '';
    }

    // find first occurence of table to find true name of optiontext column
    public static function getForeignkeyReferenceFields ($table, $foreignkeyfield) {
        foreach ($GLOBALS['generatorCnf']['tables'][$table] as $n => $v) {
            if ($v[0] == $GLOBALS['generatorCnf']['tables'][$table][$foreignkeyfield][0]) {
                return $v[1];
            }
        }
        return '';
    }

    public static function getFieldCode ($rows, $i, $table, $mode = 'form', $type = 'listing') {
        $code = "";
        $validate = (($rows[$i][2] == 'YES' && $mode != 'search') || !empty($GLOBALS['generatorCnf']['forms'][$table]['fields'][$rows[$i][0]]['override-validate'])?'':'required');
        $validationOverride = !empty($GLOBALS['generatorCnf']['forms'][$table]['fields'][$rows[$i][0]]['override-validate']);
        $validationParam = $GLOBALS['generatorCnf']['forms'][$table]['fields'][$rows[$i][0]]['validation-param'];
        $required = false;
        if (preg_match('/required/', $validate)) {
            $required = true;
        }
        if (!empty($GLOBALS['generatorCnf']['forms'][$table]['fields'][$rows[$i][0]]['validate'])) {
            $validate .= $validate?','.$GLOBALS['generatorCnf']['forms'][$table]['fields'][$rows[$i][0]]['validate']:$GLOBALS['generatorCnf']['forms'][$table]['fields'][$rows[$i][0]]['validate'];
        }
        if ($validate) {
            self::$bundleerrorcode .= 'error.'.$rows[$i][0].'='.$rows[$i][0]."<br/>\n";
            self::$bundleerrorcode .= 'error.'.$rows[$i][0].'_required='.$rows[$i][0]." nicht ausgef&uuml;llt!<br/>\n";
        }
        $sqltype = $rows[$i][1];
        if (!empty($GLOBALS['generatorCnf']['forms'][$table]['fields'][$rows[$i][0]]['control']))
            $sqltype = $GLOBALS['generatorCnf']['forms'][$table]['fields'][$rows[$i][0]]['control'];
        // do not use checkbox, if mode is 'search' => set back to whatever enum
        if ($sqltype == 'checkbox' && $mode == 'search') {
            $sqltype = $rows[$i][1];
        }
        $valuecode = $mode=='search'?'searchform'.self::upperFirstLetter($table).'->'.$rows[$i][0].'':'fn:alt('.$rows[$i][0].', editObj->'.$rows[$i][0].')';
        $value = ' value="${'.$valuecode.'}"';
        $fieldname  = $mode=='search'?"searchform".self::upperFirstLetter($table).'['.$rows[$i][0].']':$rows[$i][0];
        $tagattributes = self::getTagAttributes($table, $rows[$i][0]);
        $cssclassprefix = ($mode=='search'?'search':'');
//        if (is_array($GLOBALS['generatorCnf']['tables'][getTableName($table)][$rows[$i][0]]) || $type == 'chooser') {
        if (is_array($GLOBALS['generatorCnf']['tables'][$table][$rows[$i][0]]) || $type == 'chooser') {
            if ($type == 'chooser') {
                $tablecnf = $GLOBALS['generatorCnf']['forms'][$table]['fields'][$rows[$i][0]]['chooserconf'];
            } else {
//                $tablecnf = $GLOBALS['generatorCnf']['tables'][getTableName($table)][$rows[$i][0]];
                $tablecnf = $GLOBALS['generatorCnf']['tables'][$table][$rows[$i][0]];
            }
            $optiontext = self::getOptiontextColumn($table, $rows[$i][0]);
            if ($sqltype == 'chooser' || $type == 'chooser') {
                $code .= '<input pspc="h:input" '.($validate?'validate="'.$validate.'"':'').' '.($validationParam?'validationParam="'.$validationParam.'"':'').' type="hidden" id="'.str_replace(']','_',str_replace('[','_',$fieldname)).'_formfield" name="'.$fieldname.'" '.$value.'/>
                    <input type="hidden" id="'.str_replace(']','_',str_replace('[','_',$fieldname)).'_formfield_hold" name="'.str_replace(']','_',str_replace('[','_',$fieldname)).'_hold" value="${'.str_replace(']','_',str_replace('[','_',$fieldname)).'_hold}"/>
                    <span id="'.str_replace(']','_',str_replace('[','_',$fieldname)).
                    '_text">'.
                    ($mode=='search'?'<c:if test="${'.$valuecode.'}">[...]</c:if>':
                        ($GLOBALS['generatorCnf']['selfref'][getTableName($table)]?'<c:execute action="'.self::genClassName($table).'Action::_showSelfrefName"><c:actionparam name="id" value="${'.$valuecode.'}"/></c:execute>':'${fn:alt('.str_replace(']','_',str_replace('[','_',$fieldname)).'_hold, editObj->'.$tablecnf[1].')}')).'</span> <a href="#" onclick="return openChooser(\'<c:url action="'.
                    self::genActionMappingName($tablecnf[0]).'::chooser"><c:param name="openerfield" value="'.
                        str_replace(']','_',str_replace('[','_',$fieldname)).'_formfield"/><c:param name="openertext" value="'.
                        str_replace(']','_',str_replace('[','_',$fieldname)).'_text"/><c:param name="versiondate" value="${versiondate?versiondate:\'reset\'}"/>'.
                        '<c:param name="databasefield" value="'.
                        $optiontext.'"/></c:url>\', \''.$table.'Chooser\');"><fmt:message'.(isset($GLOBALS['generatorCnf']['options']['bundle-value-resource-path'])?' assetUrl="'.$GLOBALS['generatorCnf']['options']['bundle-value-resource-path'].'"':'').' key="choose"/></a> '.($required?'':'<a href="#" onclick="return removeChoise(\''.str_replace(']','_',str_replace('[','_',$fieldname)).'_text\', \''.str_replace(']','_',str_replace('[','_',$fieldname)).'_formfield\');"><fmt:message'.(isset($GLOBALS['generatorCnf']['options']['bundle-value-resource-path'])?' assetUrl="'.$GLOBALS['generatorCnf']['options']['bundle-value-resource-path'].'"':'').' key="delete"/></a>');
            } else {
                $code .= '<select pspc="h:selectBox" name="'.$fieldname.'"
                    '.($validate?'validate="'.$validate.'"':'').'
                    '.($validationParam?'validationParam="'.$validationParam.'"':'').'
                    selected="'.($mode=='search'?'${searchform'.self::upperFirstLetter($table).'->'.$rows[$i][0].'}':'${fn:alt('.$rows[$i][0].', editObj->'.$rows[$i][0].')}').'"
                    optionvalue="id"
                    '.($mode=='search'?'id="searchfield'.$rows[$i][0].'"':'').'
                    class="'.$cssclassprefix.'selectBox"
                    optiontext="'.$optiontext.'"
                    value="${objList_'.$rows[$i][0].'}"'.$tagattributes.'>'.
                    ($mode == 'search'||$rows[$i][0]==$table.'_parent_id'||$rows[$i][2]=='YES'?'<option value=""></option>':'').
                    '</select>';
            }
        } elseif (preg_match('/^checkbox/i',$sqltype)) {
            preg_match("/^enum\((.*?),.*\)/", $rows[$i][1], $matches);

            $checked =  "\n".'                    checked="${'.($mode=='search'?'searchform'.self::upperFirstLetter($table).'->'.$rows[$i][0]:'fn:alt('.$rows[$i][0].', tmp_checkVal)').'=='.$matches[1].'?\'checked\':\'\'}"';
            $value   =  "\n".'                    value="${'.$matches[1].'}"';
            $code .= '<c:set var="tmp_checkVal" value="${validationErrors->hasErrors?\'\':editObj->'.$rows[$i][0].'}"/><input class="'.$cssclassprefix.'checkboxfield" pspc="h:input"'.$value.$checked.'
                    name="'.$fieldname.'"
                    '.($mode=='search'?'id="searchfield'.$rows[$i][0].'"':'').'
                    type="checkbox"
                    validationErrorClass="valError"'.$tagattributes.'/>';
        } elseif (preg_match('/^(tiny|small|medium|big)?int/i',$sqltype)) {
            $code .= '<input class="'.$cssclassprefix.'numberfield" pspc="h:input"'.$value.'
                    name="'.$fieldname.'"
                    '.($mode=='search'?'id="searchfield'.$rows[$i][0].'"':'').'
                    validate="'.$validate.($validate?',':'').'number"
                    '.($validationParam?'validationParam="'.$validationParam.'"':'').'
                    validationErrorClass="valError"'.$tagattributes.'/>';
            self::$bundleerrorcode .= 'error.'.$rows[$i][0].'_number='.$rows[$i][0]."<br/>\n";
        } elseif (preg_match('/^varchar\((.*)\)/i',$sqltype,$matches)) {
            $code .= '<input class="'.$cssclassprefix.'textfield" pspc="h:input"'.$value.'
                    maxlength="'.$matches[1].'"
                    name="'.$fieldname.'"
                    '.($mode=='search'?'id="searchfield'.$rows[$i][0].'"':'').'
                    '.($validate?'validate="'.$validate.'"':'').'
                    '.($validationParam?'validationParam="'.$validationParam.'"':'').'
                    validationErrorClass="valError"'.$tagattributes.'/>';
        } elseif (preg_match('/^char\((.*)\)/i',$sqltype,$matches)) {
            $code .= '<input class="'.$cssclassprefix.'textfield" pspc="h:input"'.$value.'
                    maxlength="'.$matches[1].'"
                    name="'.$fieldname.'"
                    '.($mode=='search'?'id="searchfield'.$rows[$i][0].'"':'').'
                    validate="'.$validate.($validate?',':'').'minlength"
                    validationParam="min:'.$matches[1].($validationParam?';'.$validationParam:'').'"
                    validationErrorClass="valError"'.$tagattributes.'/>';
        } elseif ($mode != 'search' && preg_match('/^text/i',$sqltype,$matches)) {
            $code .= '<textarea pspc="h:textarea"
                    rows="5"
                    cols="24"
                    name="'.$fieldname.'"
                    '.($mode=='search'?'id="searchfield'.$rows[$i][0].'"':'').'
                    class="'.$cssclassprefix.'TextArea"
                    '.($validate?'validate="'.$validate.'"':'').'
                    '.($validationParam?'validationParam="'.$validationParam.'"':'').'
                    validationErrorClass="valError"'.$tagattributes.'>'.($mode=='search'?'${searchform'.self::upperFirstLetter($table).'->'.$rows[$i][0].'}':'${fn:alt('.$rows[$i][0].', editObj->'.$rows[$i][0].')}').'</textarea>';
        } elseif (preg_match('/^double/i',$sqltype)) {
            $code .= '<input class="'.$cssclassprefix.'numberfield" pspc="h:input"'.$value.'
                    name="'.$fieldname.'"
                    '.($mode=='search'?'id="searchfield'.$rows[$i][0].'"':'').'
                    validate="'.$validate.($validate?',':'').'englishDecimal"
                    '.($validationParam?'validationParam="'.$validationParam.'"':'').'
                    validationErrorClass="valError"'.$tagattributes.'/>';
            self::$bundleerrorcode .= 'error.'.$rows[$i][0].'_englishDecimal='.$rows[$i][0]."<br/>\n";
        } elseif (preg_match('/^float/i',$sqltype)) {
            $code .= '<input class="'.$cssclassprefix.'numberfield" pspc="h:input"'.$value.'
                    name="'.$fieldname.'"
                    '.($mode=='search'?'id="searchfield'.$rows[$i][0].'"':'').'
                    validate="'.$validate.($validate?',':'').'englishDecimal"
                    '.($validationParam?'validationParam="'.$validationParam.'"':'').'
                    validationErrorClass="valError"'.$tagattributes.'/>';
            self::$bundleerrorcode .= 'error.'.$rows[$i][0].'_englishDecimal='.$rows[$i][0]."<br/>\n";
        } elseif (preg_match('/^(decimal|dec)/i',$sqltype)) {
            $code .= '<input class="'.$cssclassprefix.'numberfield" pspc="h:input"'.$value.'
                    name="'.$fieldname.'"
                    '.($mode=='search'?'id="searchfield'.$rows[$i][0].'"':'').'
                    validate="'.$validate.($validate?',':'').'englishDecimal"
                    '.($validationParam?'validationParam="'.$validationParam.'"':'').'
                    validationErrorClass="valError"'.$tagattributes.'/>';
            self::$bundleerrorcode .= 'error.'.$rows[$i][0].'_englishDecimal='.$rows[$i][0]."<br/>\n";
        } elseif (preg_match('/^datetime/i',$sqltype)) {
            $code .= '<input class="'.$cssclassprefix.'datetimefield datetimepicker" pspc="h:input"'.$value.'
                    name="'.$fieldname.'"
                    id="'.($mode=='search'?'searchfield'.$rows[$i][0]:$fieldname).'"
                    '.($mode=='search'?'id="searchfield'.$rows[$i][0].'"':'').'
                    validate="'.$validate.($validate?',':'').'regex"
                    '.(!$validationOverride?
                            'validationParam="pattern:#\d{4}\-\d{2}\-\d{2} +\d{2,3}\:\d{2}(\:\d{2})?#'.($validationParam?';'.$validationParam:'').'"'
                            :($validationParam?'validationParam="'.$validationParam.'"':'')).'
                    validationErrorClass="valError"'.$tagattributes.'/>';
                    /* validationErrorClass="valError"'.$tagattributes.'/><button onclick="return false;" '.($mode=='search'?'id="searchfield'.$rows[$i][0].'-trigger"':'id="'.$fieldname.'-trigger"').' class="datefieldbutton">...</button>
                    <script type="text/javascript">
                        Calendar.setup({
                            inputField : "'.($mode=='search'?'searchfield'.$rows[$i][0]:$fieldname).'",
                            trigger    : "'.($mode=='search'?'searchfield'.$rows[$i][0].'-trigger':$fieldname.'-trigger').'",
                            showTime   : 24,
                            onSelect   :  function updateFields(cal) {
                                  var date = this.selection.get();
                                  if (date) {
                                          date = Calendar.intToDate(date);
                                          document.getElementById("'.($mode=='search'?'searchfield'.$rows[$i][0]:$fieldname).'").value = Calendar.printDate(date, "%Y-%m-%d " + this.getHours()+":" + this.getMinutes());
                                  }
                                  this.hide();
                            }
                        });
                    </script>';*/
            self::$bundleerrorcode .= 'error.'.$rows[$i][0].'_regex='.$rows[$i][0]."<br/>\n";
        } elseif (preg_match('/^date/i',$sqltype)) {
            $code .= '<input class="'.$cssclassprefix.'datefield datepicker" pspc="h:input"'.$value.'
                    name="'.$fieldname.'"
                    '.($mode=='search'?'id="searchfield'.$rows[$i][0].'"':'id="'.$fieldname.'"').'
                    validate="'.$validate.($validate?',':'').'regex"
                    '.(!$validationOverride?
                            'validationParam="pattern:#\d{4}\-\d{2}\-\d{2}#'.($validationParam?';'.$validationParam:'').'"'
                            :($validationParam?'validationParam="'.$validationParam.'"':'')).'
                    validationErrorClass="valError"'.$tagattributes.'/>';
                    /* validationErrorClass="valError"'.$tagattributes.'/><button onclick="return false;" '.($mode=='search'?'id="searchfield'.$rows[$i][0].'-trigger"':'id="'.$fieldname.'-trigger"').' class="datefieldbutton">...</button>
                    <script type="text/javascript">
                        Calendar.setup({
                            inputField : "'.($mode=='search'?'searchfield'.$rows[$i][0]:$fieldname).'",
                            trigger    : "'.($mode=='search'?'searchfield'.$rows[$i][0].'-trigger':$fieldname.'-trigger').'",
                            onSelect   : function() { this.hide() }
                        });
                    </script>';*/
            self::$bundleerrorcode .= 'error.'.$rows[$i][0].'_regex='.$rows[$i][0]."<br/>\n";
        } elseif (preg_match('/^time/i',$sqltype)) {
            $code .= '<input class="'.$cssclassprefix.'timefield" pspc="h:input"'.$value.'
                    name="'.$fieldname.'"
                    '.($mode=='search'?'id="searchfield'.$rows[$i][0].'"':'').'
                    validate="'.$validate.($validate?',':'').'regex"
                    '.(!$validationOverride?
                            'validationParam="pattern:#\d{2,3}\:\d{2}(\:\d{2})?#'.($validationParam?';'.$validationParam:'').'"'
                            :($validationParam?'validationParam="'.$validationParam.'"':'')).'
                    validationErrorClass="valError"'.$tagattributes.'/>';
            self::$bundleerrorcode .= 'error.'.$rows[$i][0].'_regex='.$rows[$i][0]."<br/>\n";
        } elseif ($mode != 'search' && preg_match('/^(blob|mediumblob|longblob)/i',$sqltype)) {
            $blobview = '<c:if test="${fn:preg_match(\'/^image/\', editObj->'.$rows[$i][0].'_type)}">
                        <c:url action="'.self::genActionMappingName($table).'::viewBlob" var="viewBlobURL">
                            <c:param name="id" value="${editObj->id}"/>
                            <c:param name="field" value="'.$rows[$i][0].'"/>
                            <c:param name="resize" value="200"/>
                        </c:url>
                        <img rel="lightbox[img]" src="${viewBlobURL}" style="max-width:200px;max-height:200px" class="form-mini-image"/><br/>
                    </c:if>
                    ${editObj->'.$rows[$i][0].'_filename}<br/>
                    ${fn:formatFilesize(editObj->'.$rows[$i][0].'_size)}<br/>
                    ';
            if ($formtype == 'save') {
                $code .= '<c:if test="${editObj->'.$rows[$i][0].'}">'.$blobview.'<input pspc="h:input" type="checkbox" name="'.$rows[$i][0].'_delete" value="Y"/><label for="'.$rows[$i][0].'_delete">l&ouml;schen</label><br/></c:if>
                    <input pspc="h:input" class="'.$cssclassprefix.'blobfield" type="file"'.$value.'
                    name="'.$fieldname.'"
                    '.($mode=='search'?'id="searchfield'.$rows[$i][0].'"':'').'
                    '.($validate?'validate="'.$validate.'"':'').'
                    '.($validationParam?'validationParam="'.$validationParam.'"':'').'
                    validationErrorClass="valError"'.$tagattributes.'/>';
            } elseif ($formtype == 'create') {
                $code .= '<input pspc="h:input" class="'.$cssclassprefix.'blobfield" type="file"'.$value.'
                    name="'.$fieldname.'"
                    '.($mode=='search'?'id="searchfield'.$rows[$i][0].'"':'').'
                    '.($validate?'validate="'.$validate.'"':'').'
                    '.($validationParam?'validationParam="'.$validationParam.'"':'').'
                    validationErrorClass="valError"'.$tagattributes.'/>';
            } else {
                $code .= '<c:if test="${formAction==\'save\'&&editObj->'.$rows[$i][0].'}">'.$blobview.'<input pspc="h:input" type="checkbox" name="'.$rows[$i][0].'_delete" value="Y"/><label for="'.$rows[$i][0].'_delete">l&ouml;schen</label><br/></c:if>
                    <input pspc="h:input" class="'.$cssclassprefix.'blobfield" type="file"'.$value.'
                    name="'.$fieldname.'"
                    '.($mode=='search'?'id="searchfield'.$rows[$i][0].'"':'').'
                    '.($validate?'validate="'.$validate.'"':'').'
                    '.($validationParam?'validationParam="'.$validationParam.'"':'').'
                    validationErrorClass="valError"'.$tagattributes.'/>';
            }
        } elseif (preg_match('/^enum\((.*)\)/i',$sqltype, $matches)) {
            $useBundes = false;
            $options = preg_split("/ *, */", $matches[1]);
            $optionStrArr = array();
            $optionArr = array();
            foreach ($options as $option) {
                //stdBundle[globalScope->cnf->locale]->ma_Typ_rt
                $_arr = "fn:aa(fn:array('id', $option";
                if ($useBundes) {
                    $_arr .= ",'text', stdBundle[globalScope->cnf->locale]->{$fieldname}_".substr($option, 1, strlen($option)-2);
                }
                $_arr .= "))";

                $optionArr[] = $_arr;
                $optionStrArr[] = preg_replace("/'/", "",$option);
            }
            print "Attrs $fieldname: ".$tagattributes."\n";
            $code .= '<select pspc="h:selectBox" name="'.$fieldname.'"
                    '.($mode=='search'?'id="searchfield'.$rows[$i][0].'"':'').'
                    class="'.$cssclassprefix.'selectBox"
                    validate="'.$validate.($validate?',':'').'regex" validationParam="pattern:#('.join('|',$optionStrArr).')#"
                    selected="'.($mode=='search'?'${searchform'.self::upperFirstLetter($table).'->'.$rows[$i][0].'}':'${fn:alt('.$rows[$i][0].', editObj->'.$rows[$i][0].')}').'"
                    optionvalue="id"
                    optiontext="'.($useBundes?'text':'id').'"
                    value="${fn:array('.join(', ', $optionArr).')}"'.$tagattributes.'>'.($mode == 'search'?'<option value=""></option>':'').'</select>';
            self::$bundleerrorcode .= 'error.'.$rows[$i][0].'_regex='.$rows[$i][0]."<br/>\n";
        }
        return $code.($required&&$mode!='search'&&$sqltype!='checkbox'?' *':'');
    }

    public static function getMixin ($table, $type = "action") {
        if (empty($GLOBALS['generatorCnf']['options']['mixin-dir']) || !file_exists($GLOBALS['generatorCnf']['options']['mixin-dir'])) {
            die ('Mixin dir '.$GLOBALS['generatorCnf']['options']['mixin-dir'].' does not exist!'."\n");
        } else {
            if (!file_exists($GLOBALS['generatorCnf']['options']['mixin-dir'].'/'.$type.'/'.$table.'.php')) return;
            print "include mixin '".$type.'/'.$table.'.php'."'\n";
            $content = file($GLOBALS['generatorCnf']['options']['mixin-dir'].'/'.$type.'/'.$table.'.php');
            $returnstring = "";
            $begun = false;
            foreach ($content as $line) {
                if (!$begun && preg_match('#/\* *mixin +begin *\*/#',$line)) {
                    $begun = true;
                    continue;
                } elseif ($begun && preg_match('#/\* *mixin +end *\*/#',$line)) {
                    return $returnstring;
                }
                if ($begun) {
                    $returnstring .= $line;
                }
            }
            return $returnstring;
        }
    }

    public static function getViewMixin ($table, $type = 'show') {
        if (empty($GLOBALS['generatorCnf']['options']['mixin-dir']) || !file_exists($GLOBALS['generatorCnf']['options']['mixin-dir'])) {
            die ('Mixin dir '.$GLOBALS['generatorCnf']['options']['mixin-dir'].' does not exist!'."\n");
        } else {
            $filename = $GLOBALS['generatorCnf']['options']['mixin-dir'].'/view/'.$type.'/'.$table.'.psp';
            if (!file_exists($filename)) return;
            print "mixin found: ".$filename."\n";
            return file_get_contents($filename);
        }
    }

    public static function generateOrderingConstraints ($table, $varname = 'formdata') {
        if (is_array($GLOBALS['generatorCnf']['options']['ordering'][$table]['groupcolumn'])) {
            $str = '';
            foreach ($GLOBALS['generatorCnf']['options']['ordering'][$table]['groupcolumn'] as $col) {
                $str .= '$fields[] = array(\''.
                        $col.'\', $'.$varname.'[\''.$col.'\']);'."\n";

            }
            return $str;
        } elseif (isset($GLOBALS['generatorCnf']['options']['ordering'][$table]['groupcolumn'])) {
            return '$fields[] = array(\''.
                        $GLOBALS['generatorCnf']['options']['ordering'][$table]['groupcolumn'].'\', $'.$varname.'[\''.$GLOBALS['generatorCnf']['options']['ordering'][$table]['groupcolumn'].'\']);';
        }
    }

    public static function generateOrderingFieldlist ($table, $varname = 'formdata') {
        if (is_array($GLOBALS['generatorCnf']['options']['ordering'][$table]['groupcolumn'])) {
            return ','.join(',', $GLOBALS['generatorCnf']['options']['ordering'][$table]['groupcolumn']);
        } elseif (isset($GLOBALS['generatorCnf']['options']['ordering'][$table]['groupcolumn'])) {
            return ','.$GLOBALS['generatorCnf']['options']['ordering'][$table]['groupcolumn'];
        }
    }

    public static function generateOrderingWhereClause ($table) {
        if (is_array($GLOBALS['generatorCnf']['options']['ordering'][$table]['groupcolumn'])) {
            $conds = array();
            foreach ($GLOBALS['generatorCnf']['options']['ordering'][$table]['groupcolumn'] as $col) {
                $conds[] = $col.' = ".$obj["'.$col.'"]."';
            }
            return join(' and ', $conds).' and ';
        } elseif (isset($GLOBALS['generatorCnf']['options']['ordering'][$table]['groupcolumn'])) {
            return $GLOBALS['generatorCnf']['options']['ordering'][$table]['groupcolumn'].' = ".$obj["'.$GLOBALS['generatorCnf']['options']['ordering'][$table]['groupcolumn'].'"]." and ';
        }
    }


}

?>